const express = require('express')
const router = express.Router()
const db = require('../config/database')

/**
 * 获取小说列表
 * GET /api/novels
 * Query params: category, sort, search, limit, offset
 */
router.get('/', async (req, res) => {
  try {
    const {
      category,
      sort = 'updated_at',
      search,
      limit = 20,
      offset = 0
    } = req.query

    let query = `
      SELECT * FROM novels 
      WHERE 1=1
    `

    const params = []

    // 按分类筛选
    if (category) {
      query += ' AND category = ?'
      params.push(category)
    }

    // 搜索功能
    if (search) {
      query += ' AND (title LIKE ? OR description LIKE ? OR author LIKE ?)'
      params.push(`%${search}%`, `%${search}%`, `%${search}%`)
    }

    // 排序
    switch (sort) {
      case 'popular':
        query += ' ORDER BY view_count DESC'
        break
      case 'latest':
        query += ' ORDER BY updated_at DESC'
        break
      case 'rating':
        query += ' ORDER BY rating DESC'
        break
      default:
        query += ' ORDER BY updated_at DESC'
    }

    // 分页
    query += ` LIMIT ${parseInt(limit)} OFFSET ${parseInt(offset)}`

    const novels = await db.query(query, params)

    // 处理数据格式
    const formattedNovels = novels.map(novel => ({
      ...novel,
      tags: novel.tags || []
    }))

    res.json({
      success: true,
      data: formattedNovels,
      total: formattedNovels.length
    })
  } catch (error) {
    console.error('获取小说列表失败:', error)
    res.status(500).json({
      success: false,
      message: '获取小说列表失败'
    })
  }
})

/**
 * 获取推荐小说
 * GET /api/novels/recommendations
 */
router.get('/recommendations', async (req, res) => {
  try {
    const { userId, limit = 10 } = req.query

    // 简单的推荐逻辑：按评分和浏览量排序
    const query = `
      SELECT * FROM novels
      WHERE 1=1
      ORDER BY (rating * 0.4 + view_count * 0.0001 * 0.6) DESC
      LIMIT ${parseInt(limit)}
    `

    const novels = await db.query(query, [])

    const recommendations = novels.map(novel => ({
      novel: {
        ...novel,
        tags: novel.tags || []
      },
      score: Math.random() * 0.3 + 0.7, // 0.7-1.0 的随机推荐分数
      reason: '为您推荐的热门作品',
      type: 'popular'
    }))

    res.json({
      success: true,
      data: recommendations
    })
  } catch (error) {
    console.error('获取推荐小说失败:', error)
    res.status(500).json({
      success: false,
      message: '获取推荐小说失败'
    })
  }
})

/**
 * 获取小说详情
 * GET /api/novels/:id
 */
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params

    const query = `
      SELECT * FROM novels 
      WHERE id = ?
    `

    const novels = await db.query(query, [id])

    if (novels.length === 0) {
      return res.status(404).json({
        success: false,
        message: '小说不存在'
      })
    }

    const novel = novels[0]
    novel.tags = novel.tags || []

    // 获取最新章节信息
    const latestChapterQuery = `
      SELECT title, created_at 
      FROM chapters 
      WHERE novel_id = ? 
      ORDER BY chapter_number DESC 
      LIMIT 1
    `
    const latestChapter = await db.query(latestChapterQuery, [id])

    if (latestChapter.length > 0) {
      novel.last_chapter_title = latestChapter[0].title
      novel.last_chapter_time = latestChapter[0].created_at
    }

    // 增加浏览量
    await db.query(
      'UPDATE novels SET view_count = view_count + 1 WHERE id = ?',
      [id]
    )

    res.json({
      success: true,
      data: novel
    })
  } catch (error) {
    console.error('获取小说详情失败:', error)
    res.status(500).json({
      success: false,
      message: '获取小说详情失败'
    })
  }
})

/**
 * 获取小说章节列表
 * GET /api/novels/:id/chapters
 */
router.get('/:id/chapters', async (req, res) => {
  try {
    const { id } = req.params

    const query = `
      SELECT * FROM chapters 
      WHERE novel_id = ? 
      ORDER BY chapter_number ASC
    `

    const chapters = await db.query(query, [id])

    res.json({
      success: true,
      data: chapters
    })
  } catch (error) {
    console.error('获取章节列表失败:', error)
    res.status(500).json({
      success: false,
      message: '获取章节列表失败'
    })
  }
})

/**
 * 获取小说评论
 * GET /api/novels/:id/comments
 */
router.get('/:id/comments', async (req, res) => {
  try {
    const { id } = req.params
    const { limit = 20, offset = 0 } = req.query

    const query = `
      SELECT c.*, u.nickname as user_name, u.avatar_url as user_avatar
      FROM comments c
      LEFT JOIN users u ON c.user_id = u.id
      WHERE c.novel_id = ?
      ORDER BY c.created_at DESC
      LIMIT ? OFFSET ?
    `

    const comments = await db.query(query, [
      id,
      parseInt(limit),
      parseInt(offset)
    ])

    res.json({
      success: true,
      data: comments
    })
  } catch (error) {
    console.error('获取评论失败:', error)
    res.status(500).json({
      success: false,
      message: '获取评论失败'
    })
  }
})

module.exports = router
